<?php

class Regform extends Form {
    const CAPTCHA_ERROR = 'Incorrect image verification text<br/>Please try again';

    /**
     * Name of form template file
     * The name of actual template should be
     * set in sub-class
     *
     * @var string
     */
    protected $template = 'tplRegform';

    protected function doValidate() {
        $this->validateCaptcha()
                ->validateEmail()
                ->validateUsername();
    }

    protected function init() {
        $Tr = $this->oRegistry->Tr;
        $this->aVars['username_d'] = $Tr['Username will appear alongside your posts'];
        $this->aVars['username_l'] = $Tr['Username'];
    }

    /**
     * Make sure email address is valid
     * Make sure email is not already used by some
     * user
     *
     * @return object $this
     */
    protected function validateEmail() {
        $email = strtolower($this->getSubmittedValue('email'));

        if (false === Validate::email($email)) {
            $this->setError('email', 'This is not a valid email address');
        }

        $a = $this->oRegistry->Mongo->EMAILS->findOne(array('email' => $email));

        if (!empty($a)) {
            $this->setError('email', 'There is already an account with this email address. Have you already registered on our site before?');
        }

        return $this;
    }

    /**
     * Make sure username is valid
     * Make sure it's not already in use
     *
     * @return object $this
     */
    protected function validateUsername() {
        $username = strtolower($this->getSubmittedValue('username'));

        if (false === Validate::username($username)) {
            $this->setError('username', 'This username is invalid. Username must contain only letters, numbers and a hyphen and MUST start and end with letter or number and MUST be at least 3 characters long');
        }

        $aReserved = \StudyBuddy\getReservedNames();
        if (in_array($username, $aReserved)) {
            $this->setError('username', 'This username is already in use');
        }


        $a = $this->oRegistry->Mongo->USERS->findOne(array('username_lc' => $username));

        if (!empty($a)) {
            $this->setError('username', 'This username is already in use');
        }

        return $this;
    }

    /**
     *
     */
    protected function validateCaptcha() {
        if (!empty($_SESSION['reg_captcha'])) {
            return $this;
        }

        $oCaptcha = Captcha::factory($this->oRegistry);
        $res = $oCaptcha->validate_submit();
        /**
         * If validation good then
         * all is OK
         */
        if (1 === $res) {
            $_SESSION['reg_captcha'] = true;

            return $this;
        }

        /**
         * If 3 then reached the limit of attampts
         */
        if (3 === $res) {
            throw new \StudyBuddy\CaptchaLimitException('You have reached the limit of image verification attempts');
        }

        if (Request::isAjax()) {
            $aRet = array(
                'exception' => self::CAPTCHA_ERROR,
                'fields' => array('private_key'),
                'captcha' => $oCaptcha->getCaptchaArray()
            );

            \StudyBuddy\Responder::sendJSON($aRet);
        }

        /**
         * @todo translate string
         */
        $this->setFormError(self::CAPTCHA_ERROR);

        return $this;
    }

}
